package com.ywj.demo02_concurrent_problem;

import java.util.ArrayList;
import java.util.List;

public class Test02Atomicity {
    //1.定义一个共享变量number
    private static int number = 0;
    private static Object obj = new Object();
    public static void main(String[] args) throws InterruptedException {
        //2.对number进行1000的++操作
        Runnable increment = () -> {
            for (int i = 0; i < 1000; i++) {
                //需要锁对象，故创建一把锁
                synchronized (obj) {  //obj为锁对象，也可使用synchronized (Test02Atomicity.class)
                    number++; //synchronized保证 number++ 为原子操作。线程获取不到锁 就会等待
                }
            }
        };

        List<Thread> list = new ArrayList<>();
        //3.使用5个线程来进行
        for (int i = 0; i < 5; i++) {
            Thread t = new Thread(increment);
            t.start();
            list.add(t);
        }

        for (Thread thread : list) {
            //让主线程等待自己创建的线程执行完毕
            thread.join();
        }

        System.out.println("number=" + number);  //5000

    }
}
